package com.example.agriapp.model;


import android.content.ContentProvider;
import android.content.ContentUris;
import android.content.ContentValues;
import android.content.Context;
import android.content.UriMatcher;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.net.Uri;
import android.util.Log;

import com.example.agriapp.data.AgriDatabaseHelper;
import com.example.agriapp.model.bean.FeedItem;

import java.util.ArrayList;
import java.util.List;

public class FeedContentProvider extends ContentProvider {
    private static final String TAG = "FeedContentProvider";
    private AgriDatabaseHelper dbHelper;

    public static final int FEEDS = 100;    // 多条动态
    public static final int FEED_ID = 101;  // 单条动态

    // URI匹配器
    private static final UriMatcher uriMatcher = new UriMatcher(UriMatcher.NO_MATCH);

    static {
        uriMatcher.addURI(FeedContract.AUTHORITY, "feeds", FEEDS);
        uriMatcher.addURI(FeedContract.AUTHORITY, "feeds/#", FEED_ID);
    }

    @Override
    public boolean onCreate() {
        Context context = getContext();
        if (context == null) {
            Log.e(TAG, "Context is null, cannot initialize dbHelper");
            return false;
        }
        dbHelper = new AgriDatabaseHelper(getContext());
        return true;
    }

    @Override
    public Cursor query(Uri uri, String[] projection, String selection,
                        String[] selectionArgs, String sortOrder) {
        // 确保dbHelper已初始化
        if (dbHelper == null) {
            Context context = getContext();
            if (context == null) {
                throw new IllegalStateException("Context is null, cannot initialize dbHelper");
            }
            dbHelper = new AgriDatabaseHelper(context);
            Log.d(TAG, "Reinitialized dbHelper in query()");
        }
        
        SQLiteDatabase db = dbHelper.getReadableDatabase();
        Cursor cursor;

        switch (uriMatcher.match(uri)) {
            case FEEDS:
                cursor = db.query(FeedContract.FeedEntry.TABLE_NAME,
                        projection, selection, selectionArgs,
                        null, null, sortOrder);
                break;
            case FEED_ID:
                selection = FeedContract.FeedEntry._ID + "=?";
                selectionArgs = new String[]{uri.getLastPathSegment()};
                cursor = db.query(FeedContract.FeedEntry.TABLE_NAME,
                        projection, selection, selectionArgs,
                        null, null, sortOrder);
                break;
            default:
                throw new IllegalArgumentException("Unknown URI " + uri);
        }

        cursor.setNotificationUri(getContext().getContentResolver(), uri);
        return cursor;
    }

    @Override
    public Uri insert(Uri uri, ContentValues values) {
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        long id = db.insert(FeedContract.FeedEntry.TABLE_NAME, null, values);

        if (id == -1) {
            Log.e(TAG, "Failed to insert row for " + uri);
            return null;
        }

        getContext().getContentResolver().notifyChange(uri, null);
        return ContentUris.withAppendedId(uri, id);
    }

    @Override
    public int update(Uri uri, ContentValues values, String selection,
                      String[] selectionArgs) {
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        int rowsUpdated;

        switch (uriMatcher.match(uri)) {
            case FEEDS:
                rowsUpdated = db.update(FeedContract.FeedEntry.TABLE_NAME,
                        values, selection, selectionArgs);
                break;
            case FEED_ID:
                selection = FeedContract.FeedEntry._ID + "=?";
                selectionArgs = new String[]{uri.getLastPathSegment()};
                rowsUpdated = db.update(FeedContract.FeedEntry.TABLE_NAME,
                        values, selection, selectionArgs);
                break;
            default:
                throw new IllegalArgumentException("Unknown URI " + uri);
        }

        if (rowsUpdated != 0) {
            getContext().getContentResolver().notifyChange(uri, null);
        }

        return rowsUpdated;
    }

    @Override
    public int delete(Uri uri, String selection, String[] selectionArgs) {
        SQLiteDatabase db = dbHelper.getWritableDatabase();
        int rowsDeleted;

        switch (uriMatcher.match(uri)) {
            case FEEDS:
                rowsDeleted = db.delete(FeedContract.FeedEntry.TABLE_NAME,
                        selection, selectionArgs);
                break;
            case FEED_ID:
                selection = FeedContract.FeedEntry._ID + "=?";
                selectionArgs = new String[]{uri.getLastPathSegment()};
                rowsDeleted = db.delete(FeedContract.FeedEntry.TABLE_NAME,
                        selection, selectionArgs);
                break;
            default:
                throw new IllegalArgumentException("Unknown URI " + uri);
        }

        if (rowsDeleted != 0) {
            getContext().getContentResolver().notifyChange(uri, null);
        }

        return rowsDeleted;
    }

    @Override
    public String getType(Uri uri) {
        switch (uriMatcher.match(uri)) {
            case FEEDS:
                return "vnd.android.cursor.dir/vnd." + FeedContract.AUTHORITY + ".feeds";
            case FEED_ID:
                return "vnd.android.cursor.item/vnd." + FeedContract.AUTHORITY + ".feeds";
            default:
                throw new IllegalArgumentException("Unknown URI " + uri);
        }
    }

    // 自定义方法：获取最新动态(按时间降序)
    public List<FeedItem> getLatestFeeds() {
        List<FeedItem> feeds = new ArrayList<>();
        Cursor cursor = query(FeedContract.CONTENT_URI,
                null, null, null,
                FeedContract.FeedEntry.COLUMN_DATE + " DESC");

        if (cursor != null) {
            while (cursor.moveToNext()) {
                feeds.add(cursorToFeedItem(cursor));
            }
            cursor.close();
        }

        return feeds;
    }

    // 自定义方法：更新点赞数
    public void updateLikeCount(String feedId, int delta) {
        ContentValues values = new ContentValues();
        values.put(FeedContract.FeedEntry.COLUMN_LIKES,
                FeedContract.FeedEntry.COLUMN_LIKES + " + " + delta);

        update(ContentUris.withAppendedId(FeedContract.CONTENT_URI, Long.parseLong(feedId)),
                values, null, null);
    }

    // 自定义方法：更新关注状态
    public void updateFollowStatus(String userId, boolean follow) {
        ContentValues values = new ContentValues();
        values.put(FeedContract.FeedEntry.COLUMN_IS_FOLLOWED, follow ? 1 : 0);

        update(FeedContract.CONTENT_URI, values,
                FeedContract.FeedEntry.COLUMN_USER_ID + " = ?", new String[]{userId});
    }

    // 自定义方法：插入新动态
    public void insertFeed(FeedItem feed) {
        ContentValues values = new ContentValues();
        values.put(FeedContract.FeedEntry._ID, feed.getId());
        values.put(FeedContract.FeedEntry.COLUMN_USER_ID, feed.getUserId());
        values.put(FeedContract.FeedEntry.COLUMN_USERNAME, feed.getUsername());
        values.put(FeedContract.FeedEntry.COLUMN_AVATAR, feed.getAvatar());
        values.put(FeedContract.FeedEntry.COLUMN_CONTENT, feed.getContent());
        values.put(FeedContract.FeedEntry.COLUMN_DATE, feed.getDate());
        values.put(FeedContract.FeedEntry.COLUMN_LIKES, feed.getLikes());
        values.put(FeedContract.FeedEntry.COLUMN_COMMENTS, feed.getComments());
        values.put(FeedContract.FeedEntry.COLUMN_HAS_SHOP, feed.hasShop());
        values.put(FeedContract.FeedEntry.COLUMN_IS_FOLLOWED, feed.isFollowed());
        values.put(FeedContract.FeedEntry.COLUMN_TAG, feed.getTag());
        values.put(FeedContract.FeedEntry.COLUMN_IMAGE_URI, feed.getImageUri());

        insert(FeedContract.CONTENT_URI, values);
    }

    // 将Cursor转换为FeedItem
    private FeedItem cursorToFeedItem(Cursor cursor) {
        return new FeedItem(
                cursor.getString(cursor.getColumnIndex(FeedContract.FeedEntry._ID)),
                cursor.getString(cursor.getColumnIndex(FeedContract.FeedEntry.COLUMN_USER_ID)),
                cursor.getString(cursor.getColumnIndex(FeedContract.FeedEntry.COLUMN_USERNAME)),
                cursor.getString(cursor.getColumnIndex(FeedContract.FeedEntry.COLUMN_AVATAR)),
                cursor.getString(cursor.getColumnIndex(FeedContract.FeedEntry.COLUMN_CONTENT)),
                cursor.getString(cursor.getColumnIndex(FeedContract.FeedEntry.COLUMN_DATE)),
                cursor.getInt(cursor.getColumnIndex(FeedContract.FeedEntry.COLUMN_LIKES)),
                cursor.getInt(cursor.getColumnIndex(FeedContract.FeedEntry.COLUMN_COMMENTS)),
                cursor.getInt(cursor.getColumnIndex(FeedContract.FeedEntry.COLUMN_HAS_SHOP)) == 1,
                cursor.getInt(cursor.getColumnIndex(FeedContract.FeedEntry.COLUMN_IS_FOLLOWED)) == 1,
                cursor.getString(cursor.getColumnIndex(FeedContract.FeedEntry.COLUMN_TAG)),
                cursor.getString(cursor.getColumnIndex(FeedContract.FeedEntry.COLUMN_IMAGE_URI))
        );
    }
}